import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;

import javax.swing.JFileChooser;


public class InstCode {

	static String fileName;
	/** get the file name and pass it to the parser
	 *  
	 *  This method needs to return the file name to the parser method
	 * @throws IOException 
	 */

	public static void chooseFile() throws IOException{
		JFileChooser chooser = new JFileChooser();
		// Note: source for ExampleFileFilter can be found in FileChooserDemo,
		// under the demo/jfc directory in the Java 2 SDK, Standard Edition.



		int returnVal = chooser.showOpenDialog(chooser);
		if(returnVal == JFileChooser.APPROVE_OPTION) {
			System.out.println("You chose to open this file: " + 
					chooser.getSelectedFile().getName());     // get the file name that you need to parse.
		}
		String name = chooser.getSelectedFile().getName();
		System.out.println(name);
		
		Scanner scan = new Scanner(name).useDelimiter("\\s*.smali\\s*");
		
		fileName = scan.next();
		
		System.out.println("FILE NAME: "+fileName);
		
		parserOther(name);
		
	}
	/** modify the instrumentation code path 
	 * 
	 * @param filename
	 * @throws IOException
	 */
	public static void parserOther(String filename) throws IOException{
		
		BufferedWriter bufferedWriter = null;
		FileReader fr;

		try {
			fr = new FileReader(new File(filename));
			bufferedWriter = new BufferedWriter(new FileWriter(fileName+"smali"));

			//	        BufferedReader br = new BufferedReader(fr);
			//	        String line1 = br.readLine();
			Scanner scan = new Scanner(fr);
			
			String token1 = scan.nextLine();
			
			while (scan.hasNext()) {

				//System.out.println("line= "+ line);
				//System.out.println("line1= "+ token1);
				if (token1.startsWith(".class")){

					System.out.println("OTHER CLASS");
					//bufferedWriter.write(token1);
					//bufferedWriter.newLine();
				
					String finelist = parsing.classinfo.replaceAll(parsing.getNameOfClass, InstCode.fileName);// might need to check the .super path
					bufferedWriter.write(finelist);
					bufferedWriter.newLine();
					System.out.println(finelist);
					
					//System.out.println(parsing.classinfo);
					
				//	invoke-virtual {p0}, LHelloAndroid/workspace/HelloAndroidActivity;->print()V
				

					//bufferedWriter.newLine();
				}

				else{

					bufferedWriter.write(token1);
					
					bufferedWriter.newLine();
				}

				//line1 = br.readLine();
				token1 = scan.nextLine();
			}
			bufferedWriter.write(token1); // write the end method

			//br.close();
			scan.close();

		} catch (Exception e) {
			e.printStackTrace();

		} finally {
			//Close the BufferedWriter
			try {
				
				if (bufferedWriter != null) {
					bufferedWriter.flush();
					bufferedWriter.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}

	}
}
